﻿using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Features2D;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using JMBox.Util;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace JMBox.Utils
{
    public class ImgPoiInnerTool
    {
        /// <summary>
        /// 获取批图图片的坐标
        /// </summary>
        /// <param name="screenPath"></param>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static Location LocateOnTargetImg(string screenImgPath, string imgPath, double screenProportion, bool needDrawRect)
        {
            // 加载图像
            Mat img1 = CvInvoke.Imread(screenImgPath, ImreadModes.Grayscale);
            Mat img2 = CvInvoke.Imread(imgPath, ImreadModes.Grayscale);

            // 初始化ORB
            int numberOfFeatures = 300; // 减少特征点数量
            int edgeThreshold = 5; // 减少边缘阈值
            ORB orb = new ORB(numberOfFeatures, 1.2f, 8, edgeThreshold);

            // 检测关键点和提取描述子
            VectorOfKeyPoint keypoints1 = new VectorOfKeyPoint();
            VectorOfKeyPoint keypoints2 = new VectorOfKeyPoint();
            Mat descriptors1 = new Mat();
            Mat descriptors2 = new Mat();

            orb.DetectAndCompute(img1, null, keypoints1, descriptors1, false);
            orb.DetectAndCompute(img2, null, keypoints2, descriptors2, false);

            // 确保描述子类型是CV_8U
            if (descriptors1.Depth != DepthType.Cv8U)
            {
                descriptors1.ConvertTo(descriptors1, DepthType.Cv8U);
            }

            if (descriptors2.Depth != DepthType.Cv8U)
            {
                descriptors2.ConvertTo(descriptors2, DepthType.Cv8U);
            }

            // 确保描述子的列数相同
            if (descriptors1.Cols != descriptors2.Cols)
            {
                throw new Exception("Descriptors column count does not match.");
            }

            // 初始化BF匹配器，使用汉明距离
            BFMatcher matcher = new BFMatcher(DistanceType.Hamming);

            // 进行特征匹配
            VectorOfDMatch matches = new VectorOfDMatch();
            matcher.Match(descriptors1, descriptors2, matches);

            // 筛选好的匹配
            var goodMatches = new VectorOfDMatch();
            for (int i = 0; i < matches.Size; i++)
            {
                var currentMatch = matches[i];
                if (currentMatch.Distance < 30) // 30是距离阈值，可以根据需要调整
                {
                    goodMatches.Push(new[] { currentMatch });
                }
            }

            // 绘制匹配结果
            Mat result = new Mat();
            Features2DToolbox.DrawMatches(img1, keypoints1, img2, keypoints2, goodMatches, result, new MCvScalar(255, 0, 0), new MCvScalar(0, 255, 0), null);

            // 显示结果
            CvInvoke.Imshow("Matched Features", result);
            CvInvoke.WaitKey(0);
            CvInvoke.DestroyAllWindows();
            return new Location(-1, -1, -1);
        }

    }
}
